package cn.com.io.day20151215;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 实现将内容追加到文件内容后面
 */
public class RandomFileChannelTest {
    public static void main(String[] args) throws IOException {
        FileChannel randomChannel = null;
        try {
            File f = new File("RandomFileChannelTest.txt");
            randomChannel = new RandomAccessFile(f,"rw").getChannel();//创建RandomAccessFile对象，并从中获取FileChannel对象
            ByteBuffer buffer = randomChannel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());//将Channel中的所有数据映射成ByteBuffer
            randomChannel.position(f.length());//把Channel的记录指针移动到最后
            randomChannel.write(buffer);//将buffer中的所有数据输出
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (randomChannel !=null){
                randomChannel.close();
            }
        }
    }
}
